package com.senyint.sys.utils;

/**
 * 根据目录顺序生成路径
 * 
 * @author WangNaiFei
 * @version 1.0 支持路径斜杠反斜杠处理，支持多系统
 * @version 1.1 支持jar包
 */

public class FilePathUtils {

	public static final String classPath = FilePathUtils.class.getClassLoader().getResource("").getPath().replace("%20", " ");

	public static String classPathRoot(String... paths) {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(classPath);
		append(stringBuffer, paths);
		return stringBuffer.toString();
	}

	public static String pathOfWEBClasses(String... paths) {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(pathOfWEBINF("classes"));
		append(stringBuffer, paths);
		return stringBuffer.toString();
	}

	/**
	 * 获取web项目根目录
	 * 
	 * @return
	 */
	public static String pathOfWEBAppRoot(String... paths) {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(classPath.substring(0, classPath.lastIndexOf("WEB-INF")));
		append(stringBuffer, paths);
		return stringBuffer.toString();
	}

	public static String pathOfWEBINF(String... paths) {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(pathOfWEBAppRoot("WEB-INF"));
		append(stringBuffer, paths);
		return stringBuffer.toString();
	}

	public static String pathOfWEBConfig(String... paths) {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(pathOfWEBAppRoot("WEB-INF", "config"));
		append(stringBuffer, paths);
		return stringBuffer.toString();
	}

	public static String pathOfSpringBootRoot(String... dir) {
		StringBuffer stringBuffer = new StringBuffer();
		append(stringBuffer, System.getProperty("user.dir"));
		append(stringBuffer, dir);
		return stringBuffer.toString();
	}

	/**
	 * 添加目录 忽略之前目录是否斜线结束 返回 以dir结尾的目录
	 * 
	 * @param dir
	 * @return
	 * @return
	 */
	public static StringBuffer append(String... dir) {
		StringBuffer stringBuffer = new StringBuffer();
		append(stringBuffer, dir);
		return stringBuffer;
	}

	/**
	 * @Title: append
	 * @Description: 连接文件路径
	 * @author WangNaiFei,WangNaiFei@senyint.com
	 * @date 2018年4月9日 上午10:08:11
	 * @version 1.0
	 * @param stringBuffer
	 * @param dir
	 */
	public static void append(StringBuffer stringBuffer, String... dir) {
		for (String d : dir) {
			String p = stringBuffer.toString();
			if (d != null) {
				if (d.contains("\\")) { // 2个斜线表示转义一个斜线
					d = d.replaceAll("\\\\", "/"); // 4个斜线表示双斜线的转义 此处是正则 需要用双斜线表示斜线
				}
				if ("".equals(p) || p.endsWith("/") || p.endsWith("\\")) {
					stringBuffer.append(d);
				} else {
					// 下面使用“/”的目的是 解决存储和服务器的系统不一样的问题 而且兼容windows
					stringBuffer.append("/");
					stringBuffer.append(d);
				}
			}
		}
	}

	public static void main(String args[]) {
		System.out.println(FilePathUtils.classPathRoot());
		System.out.println(FilePathUtils.pathOfWEBClasses());
		System.out.println(FilePathUtils.pathOfWEBAppRoot());
		System.out.println(FilePathUtils.pathOfWEBINF());
		System.out.println(FilePathUtils.pathOfWEBConfig());
	}
}
